#!/bin/bash

###run this script after the kernel compilation is completed,
###and it will generate kernel image for rockchip embeded device.
###parameter: 
###          kernel_path: the path to the compiled kernel
###output   : boot.img
###author   : Wang Ge
###date     : 2024-05-12

Usage="Usage: $0 kernel_path"

###Variable Declaration
DTB_NAME="rk3568-lubancat-2.dtb"
IMAGE_PATH="$1/arch/arm64/boot/Image"
DTB_PATH="$1/arch/arm64/boot/dts/rockchip/$DTB_NAME"
TMP_DIR="./boot"
SUFFIX="_new"
BOOT_FILE="boot"
IMAGE_FORMAT=".img"


###script start
if [ $# -ne 1 ];then
  echo $Usage
  exit 1
fi

if [ ! -f "$IMAGE_PATH" ];then
  echo "Error: no valid Image file in $1/arch/arm64/boot"
  exit 1
fi

if [ ! -f "$DTB_PATH" ];then
  echo "Error: no valid dtb file in $1/arch/arm64/boot/dts/rockchip/"
  exit 1
fi

while [ -d "$TMP_DIR" ]
do
  TMP_DIR=$TMP_DIR$SUFFIX
done

mkdir $TMP_DIR
mkdir $TMP_DIR/extlinux
touch $TMP_DIR/extlinux/extlinux.conf

cat > $TMP_DIR/extlinux/extlinux.conf << EOF
label oe-kernel-6.6
    kernel /Image
    fdt /rk3568.dtb
    append  root=/dev/mmcblk0p3 earlyprintk console=ttyFIQ0 consoleblank=0 loglevel=7 rootwait rw rootfstype=ext4 cgroup_enable=cpuset cgroup_memory=1 cgroup_enable=memory swapaccount=1 switolb=1 coherent_pool=1m
EOF

cp $IMAGE_PATH $TMP_DIR
cp $DTB_PATH $TMP_DIR/rk3568.dtb

which genext2fs > /dev/null 2>&1
if [ $? -eq 1 ];then
  echo "Error: genext2fs not found, please install genext2fs first."
  exit 1
fi

Image_size=`ls -l $TMP_DIR/Image | awk '{print $5}'`
size_len=${#Image_size}
Image_size=`echo $Image_size | cut -c -$((size_len - 3))`

while [ -f "$BOOT_FILE$IMAGE_FORMAT" ]
do 
    BOOT_FILE=$BOOT_FILE$SUFFIX
done

genext2fs -b $((Image_size + 3000)) -d $TMP_DIR/ -i 8192 -U $BOOT_FILE$IMAGE_FORMAT

if [ -f "$BOOT_FILE$IMAGE_FORMAT" ];then
  echo "Generate kernel image $BOOT_FILE$IMAGE_FORMAT successfull"
else
  echo "genext2fs failed"
fi

rm -rf $TMP_DIR
